const path = require("path");
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
var expressJWT = require('express-jwt');
const { init: initDB, User } = require("./db");
const Router = require('./routes/index');
const { secretKey } = require('./config/config')
const logger = morgan("tiny");

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);

app.use('/uploads', express.static(path.join(__dirname, 'upload')));

app.use(expressJWT({ secret: secretKey, algorithms: ['HS256'] }).unless({
  // 全部路径不需要校验
  // path: '/*' // 匹配所有路径，不需要校验

  path: ['/api/login', '/api/getPsychologyKnowledgeList',
    '/api/register', '/api/uploadFiles']
/*addPsychologyKnowledge', 
getPsychologyKnowledgeList
updatePsychologyKnowledge'
deletePsychologyKnowledge'
likePsychologyKnowledge',  */

}))

// 自定义中间件检查用户是否存在
async function checkUserExist(req, res, next) {
  if (req.user?.id) {
    const tempUser = await User.findOne({ where: { id: req.user.id } });
    if (tempUser?.dataValues) {
      next();
    }
    else {
      return res.send({
        status: 401,
        message: "用户不存在",
      });
    }
  } else {
    next();
  }
}

// 使用自定义中间件
app.use(checkUserExist);
app.use('/api', Router);
app.get("/", async (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

app.use((err, req, res, next) => {
  // 这次错误是由 token 解析失败导致的
  console.log(err);
  
  if (err.name === "UnauthorizedError") {
    res.status = 401;
    return res.send({
      status: 401,
      message: "无效的token",
    });
  }
  res.send({
    status: 500,
    message: "未知的错误",
  });
});

// 检查数据库中是否存在管理员账号   如果没有（系统首次启动）  则创建一个默认的管理员账号
const checkAdminIfExist = async () => {
  // 查询是否存在管理员账户
  const adminCount = await User.count({ where: { is_admin: true } });

  if (adminCount === 0) {
    console.log("----------------------------------------------------------")
    console.log("No admin found. Creating default admin account......");
    console.log("----------------------------------------------------------")
    const defaultAdmin = {
      username: "admin",
      password: "admin1",
      is_admin: true
    };
    await User.create(defaultAdmin);
    console.log("----------------------------------------------------------")
    console.log("Default admin account created successfully.");
    console.log("username:", defaultAdmin.username);
    console.log("password:", defaultAdmin.password);
    console.log("----------------------------------------------------------")
  } else {
    console.log("----------------------------------------------------------")
    console.log("Admin account already exist. Skipping admin creation.");
    console.log("----------------------------------------------------------")
  }
}

const port = process.env.PORT || 4000;

async function bootstrap() {
  await initDB();
  checkAdminIfExist()
  app.listen(port, () => {
    console.log("server is running on port", port);                                               
  });
}

bootstrap();